import React, { Component } from "react";
import login from "../hooks/loginInfo";
import { Redirect } from "react-router-dom";
import "../assets/css/My.css";
import { errorToast, successToast } from "../components/Toast";
import Alert from "../components/Alert";
import Loading from "../components/Loading";

class My extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isLogin: null,
      token: null,
      userInfo: null,
      isEditName: false,
      newName: "",
      isEditDesc: false,
      newDesc: "",
    };
    this.uploadingBg = this.uploadingBg.bind(this);
    this.ToTarget = this.ToTarget.bind(this);
    this.uploadingImg = this.uploadingImg.bind(this);
    this.editName = this.editName.bind(this);
    this.affirm = this.affirm.bind(this);
    this.ChangeNewName = this.ChangeNewName.bind(this);
    this.ChangeNewDesc = this.ChangeNewDesc.bind(this);
    this.editDesc = this.editDesc.bind(this);
    this.affirmDesc = this.affirmDesc.bind(this);
  }
  affirmDesc() {
    if (this.state.newDesc.length !== 0) {
      this.$axios
        .post("/updateDesc", {
          tokenString: this.state.token,
          desc: this.state.newDesc,
        })
        .then((res) => {
          successToast(res.data.msg);
          this.setState({
            userInfo: { ...this.state.userInfo, desc: this.state.newDesc },
          });
          this.editDesc();
        });
    } else {
      errorToast("请输入简介内容");
    }
  }
  ChangeNewName(e) {
    this.setState({
      newName: e.target.value,
    });
  }
  ChangeNewDesc(e) {
    this.setState({
      newDesc: e.target.value,
    });
  }
  editName() {
    this.setState({
      isEditName: !this.state.isEditName,
      newName: "",
    });
  }
  editDesc() {
    this.setState({
      isEditDesc: !this.state.isEditDesc,
      newDesc: "",
    });
  }
  ToTarget(e) {
    this.props.history.push(e);
  }
  uploadingBg(e) {
    var suffix = e.target.value
      .slice(e.target.value.lastIndexOf(".") + 1)
      .toLowerCase();
    if (
      suffix !== "jpg" &&
      suffix !== "jpeg" &&
      suffix !== "png" &&
      suffix !== "bmp" &&
      suffix !== "gif"
    ) {
      errorToast("请上传图片");
    } else {
      var file = e.target.files[0];
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (res) => {
        var base = res.target.result;
        this.$axios
          .post("/updateUserBg", {
            tokenString: this.state.token,
            imgType: suffix,
            serverBase64Img: base.split(",")[1],
          })
          .then((res) => {
            if (res.data.code === "I001") {
              successToast("上传成功");
              this.setState({
                userInfo: { ...this.state.userInfo, userBg: res.data.userBg },
              });
            }
          });
      };
    }
  }
  componentWillMount() {
    const loginInfo = login();
    this.setState({
      isLogin: loginInfo.isLogin,
      token: loginInfo.token,
    });
    if (!loginInfo.isLogin) {
      localStorage.setItem("ToLoginPage", JSON.stringify({ path: "/my" }));
    } else {
      this.$axios
        .get("/findMy", {
          params: {
            tokenString: loginInfo.token,
          },
        })
        .then((res) => {
          this.setState({
            userInfo: res.data.result[0],
          });
        });
    }
  }
  uploadingImg(e) {
    var suffix = e.target.value
      .slice(e.target.value.lastIndexOf(".") + 1)
      .toLowerCase();
    if (
      suffix !== "jpg" &&
      suffix !== "jpeg" &&
      suffix !== "png" &&
      suffix !== "bmp" &&
      suffix !== "gif"
    ) {
      errorToast("请上传图片");
    } else {
      var file = e.target.files[0];
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (res) => {
        var base = res.target.result;
        this.$axios
          .post("/updateAvatar", {
            tokenString: this.state.token,
            imgType: suffix,
            serverBase64Img: base.split(",")[1],
          })
          .then((res) => {
            if (res.data.code === "H001") {
              successToast("上传成功");
              this.setState({
                userInfo: { ...this.state.userInfo, userImg: res.data.userImg },
              });
            }
          });
      };
    }
  }
  affirm() {
    if (this.state.newName.length > 0 && this.state.newName.length <= 10) {
      this.$axios
        .post("/updateNickName", {
          tokenString: this.state.token,
          nickName: this.state.newName,
        })
        .then((res) => {
          successToast(res.data.msg);
          this.setState({
            userInfo: { ...this.state.userInfo, nickName: this.state.newName },
          });
          this.editName();
        });
    } else {
      errorToast("昵称长度1-10位以内");
    }
  }

  MyContent() {
    return this.state.userInfo ? (
      <div className="myContent">
        <div
          className="myContent_bg"
          style={{ backgroundImage: `url(${this.state.userInfo.userBg})` }}
        >
          <input
            type="file"
            accept="image/jpg,image/jpeg,image/png,image/bmp,image/gif"
            className="myContent_bg_file"
            onChange={this.uploadingBg}
          />
        </div>
        <div className="myContent_myInfo">
          <div className="myInfo_detail">
            <div className="myInfo_detail_my">
              <div className="myInfo_detail_my_img">
                <img src={this.state.userInfo.userImg} alt="" />
                <input
                  type="file"
                  accept="image/jpg,image/jpeg,image/png,image/bmp,image/gif"
                  onChange={this.uploadingImg}
                />
              </div>
              <div className="myInfo_detail_my_text">
                <div onClick={this.editName}>
                  <span className="myInfo_detail_my_name">
                    {this.state.userInfo.nickName}
                    <i></i>
                  </span>
                </div>
                <span className="myInfo_detail_my_desc" onClick={this.editDesc}>
                  {this.state.userInfo.desc
                    ? this.state.userInfo.desc
                    : "这个家伙很懒，什么都没留下"}
                </span>
              </div>
            </div>
            <ul className="myInfo_detail_serve">
              <li onClick={() => this.ToTarget("/personalData")}>
                <span>个人资料</span>
                <i></i>
              </li>
              <li onClick={() => this.ToTarget("/myOrder")}>
                <span>我的订单</span>
                <i></i>
              </li>
              <li onClick={() => this.ToTarget("/collection")}>
                <span>我的收藏</span>
                <i></i>
              </li>
              <li onClick={() => this.ToTarget("/addressAdmin")}>
                <span>收货地址</span>
                <i></i>
              </li>
              <li onClick={() => this.ToTarget("/safetyCenter")}>
                <span>安全中心</span>
                <i></i>
              </li>
            </ul>
          </div>
        </div>
        {this.state.isEditName && (
          <Alert cancel={this.editName} affirm={this.affirm}>
            <span slot="title">修改昵称</span>
            <input
              value={this.state.newName}
              onChange={this.ChangeNewName}
              type="text"
              slot="content"
              placeholder="请输入1-10位以内的昵称"
              className="EditNameBox"
            />
          </Alert>
        )}
        {this.state.isEditDesc && (
          <Alert cancel={this.editDesc} affirm={this.affirmDesc}>
            <span slot="title">修改简介</span>
            <input
              value={this.state.newDesc}
              onChange={this.ChangeNewDesc}
              type="text"
              slot="content"
              placeholder="请输入简介"
              className="EditNameBox"
            />
          </Alert>
        )}
      </div>
    ) : (
      <Loading></Loading>
    );
  }

  render() {
    return (
      <div className="my">
        {this.state.isLogin ? (
          this.MyContent()
        ) : (
          <Redirect to="/login"></Redirect>
        )}
      </div>
    );
  }
}

export default My;
